package com.shujia.MapReduce;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class Demo4SumScore {
    public static class SumScoreMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
        @Override
        protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, IntWritable>.Context context) throws IOException, InterruptedException {
            String[] scores = value.toString().split(",");
            String id = scores[0];
            String score = scores[2];
            context.write(new Text(id), new IntWritable(Integer.parseInt(score)));
        }
    }

    public static class SumScoreReduce extends Reducer<Text, IntWritable, Text, IntWritable> {
        @Override
        protected void reduce(Text key, Iterable<IntWritable> values, Reducer<Text, IntWritable, Text, IntWritable>.Context context) throws IOException, InterruptedException {
            int sum = 0;
            for (IntWritable score : values) {
                sum += score.get();
            }
            context.write(key, new IntWritable(sum));
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        Configuration conf = new Configuration();
        // 做其他的配置

        // 创建一个Job
        Job job = Job.getInstance(conf);

        // 设置Job的名字
        job.setJobName("Demo4SumScore");
        // 设置MapReduce运行的类
        job.setJarByClass(Demo4SumScore.class);

        // 配置Map
        // 配置Map Task运行的类
        job.setMapperClass(SumScoreMapper.class);
        // 设置Map任务输出的key的类型
        job.setMapOutputKeyClass(Text.class);
        // 设置Map任务输出的value的类型
        job.setMapOutputValueClass(IntWritable.class);

        // 配置Reduce
        // 配置Reduce Task运行的类
        job.setReducerClass(SumScoreReduce.class);
        // 设置Reduce任务输出的key的类型
        job.setOutputKeyClass(Text.class);
        // 设置Reduce任务输出的value的类型
        job.setOutputValueClass(IntWritable.class);

        // 配置输入输出路径
        // 将输入的第一个参数作为输入路径，第二个参数作为输出的路径
        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        // 提交任务并等待运行结束
        job.waitForCompletion(true);
    }
}
